#############################Main Text Analyses########################

#Last run by authors on macOS Monterey v 12.1
# Rstudio verison 2022.02.3 
# Running R version 4.1.2 Bird Hippie

#Load data
#Define functions
#Produce figures from main text

#Files In: data_panel.csv, engagement_panel.csv

#Note: We use summary data to produce the figures here, since Twitter terms of use prevent sharing the raw text data.

###########################################################################
###Required packages
#install.packages('pacman')
pacman::p_load(plm, lmtest, sandwich, tidyverse, tidyr, broom, stargazer,
               fixest, this.path, bacondecomp, did, ggplot2, forcats,
               dplyr, plyr, lubridate)

#sets working directory to current folder
setwd(dirname(this.path()))

#pulls required data and functions (both for main analysis and for appendix)
source('VZ_source_code.R')

#################################################
###########Figure 1: Discussion of Foreign Action  
#################################################
#Event study
es_foreign_policy <- plm(perc_foreign_policy ~ lead_lags+month+log(num_tweets+1), data = pdf, model = "within")
es_foreign_policy_coef <- coeftest(es_foreign_policy, vcov = vcovHC(es_foreign_policy, type = "HC1", cluster = "group"))
es_foreign_policy_plot<-es_plot(es_foreign_policy_coef, 'Change in % Foreign Action Tweets')
ggsave("plots/es_foreign_policy_plot.pdf", es_foreign_policy_plot, width = 8.5, height = 6.5)


foreign_policy_models<-getting_models('perc_foreign_policy', pdf)
military_models<-getting_models('perc_military', pdf)
sanctions_models<-getting_models('perc_sanctions', pdf)
diplomacy_models<-getting_models('perc_diplomacy', pdf)

models<-list(foreign_policy_models, military_models,
             sanctions_models, diplomacy_models)

dv_names<-c('Overall Foreign Policy', 'Military Intervention', 'Economic Sanctions', 'Diplomacy')

dv_types<-c('bold', 'plain', 'plain', 'plain')

model_types<-c('Two-Way FEs', 'Month FEs', 'Time Trend')

coef_plot(models, dv_names, dv_types, model_types, 'foreign_policy', 'Foreign Policy Terms and Exile')

#######################################################
#############Figure 2: Discussion of Service Provision 
#######################################################

es_services <- plm(perc_service ~ lead_lags+month+log(num_tweets+1), data = pdf, model = "within")
es_services_coef <- coeftest(es_services, vcov = vcovHC(es_services, type = "HC1", cluster = "group"))
es_services_plot<-es_plot(es_services_coef, 'Change in % Tweets on Service Provision')
ggsave("plots/es_services_coef.pdf", es_services_plot, width = 8, height = 7)



services_models<-getting_models('perc_service', pdf)

dv_names<-c('Service Provision')

dv_types<-c('bold')

model_types<-c('Two-Way FEs', 'Month FEs', 'Time Trend')

coef_plot(services_models, dv_names, dv_types, model_types, 'services', 'Service Provision Terms and Exile')


#####################################################
#############Figure 3: Discussion of Domestic Protest 
#####################################################

#Event study
es_protest <- plm(perc_protest ~ lead_lags+month+log(num_tweets+1), data = pdf, model = "within")
es_protest_coef <- coeftest(es_protest, vcov = vcovHC(es_protest, type = "HC1", cluster = "group"))
es_protest_plot<-es_plot(es_protest_coef, 'Change in % of Tweets on Protest')
ggsave("plots/es_protest_plot.pdf", es_protest_plot, width = 8, height = 7)


#Two way fixed effects
protest_models<-getting_models('perc_protest', pdf)

models<-list(protest_models, protest_models, protest_models)

dv_names<-c('Protest')

dv_types<-c('bold')

model_types<-c('Two-Way FEs', 'Month FEs', 'Time Trend')

coef_plot(protest_models, dv_names, dv_types, model_types, 'protest', 'Protest Terms and Exile')

###################################################
#############Figure 4: Harsh Anti-Regime Criticism 
###################################################

es_criticism <- plm(perc_harsh_criticism ~ lead_lags+month+log(num_tweets+1), data = pdf, model = "within")
es_criticism_coef <- coeftest(es_criticism, vcov = vcovHC(es_criticism, type = "HC1", cluster = "group"))
es_criticism_plot<-es_plot(es_criticism_coef, 'Change in % Tweets on Harsh Criticism')
ggsave("plots/es_criticism_plot.pdf", es_criticism_plot, width = 8, height = 7)

criticism_models<-getting_models('perc_harsh_criticism', pdf)
narco_models<-getting_models('perc_narco', pdf)
dictator_models<-getting_models('perc_dictator', pdf)
cuba_models<-getting_models('perc_cuba', pdf)
repression_models<-getting_models('perc_all_repression', pdf)

list_of_m<-list(criticism_models, narco_models, dictator_models, cuba_models, repression_models)

dv_names<-c('Harsh Criticism', 'Narco-State', 'Dictator', 'Cuban/Russian Influence', 'Repression')

dv_types<-c('bold', 'plain', 'plain', 'plain', 'plain')

model_types<-c('Two-Way FEs', 'Month FEs', 'Time Trend')

coef_plot(list_of_m, dv_names, dv_types, model_types, 'criticism', 'Harsh Criticism and Exile')


##################################################
##############Figure 5: Mechanism: Foreign Actors
##################################################
#Event Study 
es_foreign <- plm(perc_all_foreign ~ lead_lags+month+log(num_tweets+1), data = pdf, model = "within")
es_foreign_coef <- coeftest(es_foreign, vcov = vcovHC(es_foreign, type = "HC1", cluster = "group"))
es_foreign_plot<-es_plot(es_foreign_coef, 'Change in % Tweets on Foreign Actors')
ggsave("plots/es_foreign_plot.pdf", es_foreign_plot, width = 8, height = 7)

#two way FE
foreign_models<-getting_models('perc_all_foreign', pdf)
us_models<-getting_models('perc_us', pdf)
engagement_models<-getting_models('perc_foreign_engagement', engagement_pdf)
english_models<-getting_models('perc_english', pdf)

models<-list(foreign_models, us_models, engagement_models, english_models)

dv_names<-c('Foreign Actors', 'US Terms', 'Foreign Engagement', 'English')

dv_types<-c('bold', 'plain', 'bold', 'bold')

model_types<-c('Two-Way FEs', 'Month FEs', 'Time Trend')

coef_plot(models, dv_names, dv_types, model_types, 'foreign', 'Foreign Content and Exile')


#####################################
#####Figure 6: Exile and Destination 
#####################################

md_US_1 <- plm(perc_us~ tweeted_exile*US_destination+month+log(num_tweets+1), data = pdf, model = "within")
coef1_US <- coeftest(md_US_1, vcov = vcovHC(md_US_1, type = "HC1", cluster = "group"))

md_colombia_1 <- plm(perc_colombia~ tweeted_exile*CO_destination+month+log(num_tweets+1), data = pdf, model = "within")
coef1_colombia <- coeftest(md_colombia_1, vcov = vcovHC(md_colombia_1, type = "HC1", cluster = "group"))

coef_df<-data.frame(tidy(coef1_US), coef.int=T)[dim(coef1_US)[1],]
coef_df_co<-data.frame(tidy(coef1_colombia), coef.int=T)[dim(coef1_colombia)[1],]
coef_df<-rbind(coef_df, coef_df_co)

coef_df$conf.low<-coef_df$estimate-coef_df$std.error*1.96
coef_df$conf.high<-coef_df$estimate+coef_df$std.error*1.96
coef_df$model<-c('Exiled in US', 'Exiled in Colombia')
coef_df$name<-c('US mentions',  'Colombia mentions')
coef_df$name<-rev(factor(coef_df$name, levels=as.character(unique(coef_df$name))))


bydestination_plot<-ggplot(coef_df, aes(shape=model,linetype=model, x=name, y=estimate))+
  geom_pointrange(aes(ymin=conf.low, ymax=conf.high), position=position_dodge(width=.3), size=.9)+
  theme_bw()+
  theme(legend.position='bottom', axis.title=element_text(size=24),
        text=element_text(size=24), axis.text=element_text(size=22))+
  coord_flip()+
  geom_hline(aes(yintercept=0), lty=4)+
  scale_y_continuous(name='Change in % tweets')+
  scale_shape_discrete(name=' ', guide=guide_legend(reverse=T))+
  scale_linetype_discrete(name=' ', guide=guide_legend(reverse=T))+
  xlab("")+scale_x_discrete(labels=unique(coef_df$name))+
  theme(plot.title = element_text(hjust = 0.5, size=18))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))
ggsave("plots/bydestination_plot.pdf", bydestination_plot, width = 8.5, height = 6.5)



sgd<-stargazer(list(coef1_US, coef1_colombia),
              title='Country Mentions by Destination',
              omit=c('month', 'trend', 'actor.id', 'Constant'),
              align=TRUE, header=FALSE, label='table:bydestination',
              column.separate = rep(length(model_types), length(dv_names)),
              covariate.labels=c('Tweeted from Exile', 'Number of Tweets', 
                                 'Tweeted from Exile * US Destination', 
                                 'Tweeted from Exile * Colombia Destination'),
              omit.stat=c('f', 'adj.rsq'),
              model.numbers=F,
              add.lines=list(c("Month/Year FE", paste(rep(c('Y', 'Y', 'Y'), length(dv_names)))),
                             c('User FE', paste(rep(c('Y', 'N', 'Y'), length(dv_names)))),
                             c('User trend', paste(rep(c('N', 'N', 'Y'), length(dv_names))))),
              
              font.size = 'footnotesize',
              column.sep.width = "-15pt",
              dep.var.labels.include=FALSE, dep.var.caption = "", no.space=TRUE,
              notes=c("Robust standard errors clustered at the user level."))
write(sgd, paste('tables/', 'bydestination', '_table.tex', sep=''))


